package com.wxy.ej.flow.modules.act.controller.beanController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rt.easyjava.common.base.MyQueryWrapper;
import com.rt.easyjava.common.base.PageDto;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.base.UserDetailsDto;
import com.rt.easyjava.common.config.dozer.MyMapper;
import com.wxy.ej.flow.modules.act.bean.FormData;
import com.wxy.ej.flow.modules.act.dto.FormDataDto;
import com.wxy.ej.flow.modules.act.service.beanService.FormDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
* 前端控制器
* 1，每个bean的Controller, 根据实际情况，查以删除不用的方法
* 2，用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，userDetailsJson)
* @author wuxiaoyong
* @since 2022-05-20
*/
@Slf4j
@Api(tags = "FormDataController -  控制类")
@RequestMapping("/coding/formData")
@Controller
public class FormDataController {
    @Autowired
    protected MyMapper mapper;
    @Autowired
    protected FormDataService formDataService;

    //@PreAuthorize("hasAuthority('activiti:formData:query')")
    @ApiOperation("分页查询列表（适合单表查询）")
    @GetMapping(value = "/page")
    @ResponseBody
    public Result page(@ModelAttribute FormDataDto formDataDto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "formData:query");
        Page<FormData> page = new Page<>(formDataDto.getPage(), formDataDto.getLimit());

        // 查询条件
        FormData formDataQuery = mapper.map(formDataDto, FormData.class);
        // set deleteflag default 0, 查询参数时，默认只查有效数据
        formDataQuery.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        formDataQuery.rebuildDataLimitQueryBean(userDetailsDto);

        QueryWrapper<FormData> queryWrapper=new QueryWrapper<>(formDataQuery);
        //特殊查询条件
        queryWrapper.ge(formDataDto.getCreateTime_Start()!=null,"create_time",formDataDto.getCreateTime_Start());
        queryWrapper.le(formDataDto.getCreateTime_End()!=null,"create_time",formDataDto.getCreateTime_End());
        // queryWrapper.orderBy(formDataDto.getCondition(), formDataDto.isAsc(), formDataDto.getColumn());
        // 支持前端：listQuery.sort='-part_no,-id'
        for (PageDto sortDto:formDataDto.getSortList()){
            queryWrapper.orderBy(true, sortDto.getAsc(), sortDto.getColumn());
        }

        return formDataService.page(page, queryWrapper);
    }

    /**
        树结构查询方法，非树结构会造一个空方法备用着。
    */
    //@PreAuthorize("hasAuthority('activiti:formData:query')")
    @ApiOperation("以ID作为父节点，查询子树")
    @GetMapping(value = "/tree")
    @ResponseBody
    public Result tree (Long id) {
        Result<FormDataDto> result = new Result<>();
        // when id=0 , id=0 is parantId=0 , 默认设置一个空根
        FormDataDto formDataDto = new FormDataDto();
        formDataDto.setId(0L);
        if (id!=0) {
            FormData formData = formDataService.getById(id);
            formDataDto = mapper.map(formData, FormDataDto.class);
        }
        treeReduce(formDataDto);
        result.setObj(formDataDto);

        return result.success();
    }

    private void treeReduce(FormDataDto formDataDto){
    }

    ////@PreAuthorize("hasAuthority('activiti:formData:query')")
    @ApiOperation("自定义sql分页查询（mapper.xml, 适合多表查询）")
    @GetMapping(value = "/myPage")
    @ResponseBody
    public Result myPage(@ModelAttribute FormDataDto formDataDto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "formData:query");
        Page<FormData> page = new Page<>(formDataDto.getPage(), formDataDto.getLimit());

        // 查询条件
        FormData formDataQuery = mapper.map(formDataDto, FormData.class);
        // set deleteflag default 0, 查询参数时，默认只查有效数据
        formDataQuery.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        formDataQuery.rebuildDataLimitQueryBean(userDetailsDto);

        // 多表查询时，plus自带不支持，这里封装一个工具类处理，mapper.xml中主表别名是t1, 给所有非空字段加别名； 特殊查询条件，在工具类中要忽略掉，最后自定义增加。
        QueryWrapper<FormData> queryWrapper = MyQueryWrapper.buildQueryWrapper(formDataQuery , "create_time");
        //特殊查询条件
        queryWrapper.ge(formDataDto.getCreateTime_Start()!=null,"t1.create_time",formDataDto.getCreateTime_Start());
        queryWrapper.le(formDataDto.getCreateTime_End()!=null,"t1.create_time",formDataDto.getCreateTime_End());
        // queryWrapper.orderBy(formDataDto.getCondition(), formDataDto.isAsc(), "t1."+formDataDto.getColumn());
        // 支持前端：listQuery.sort='-part_no,-id'
        for (PageDto sortDto:formDataDto.getSortList()){
            queryWrapper.orderBy(true, sortDto.getAsc(), "t1."+sortDto.getColumn());
        }

        return formDataService.myPage(page, queryWrapper, formDataDto.getHasFooter());
    }



    //@PreAuthorize("hasAuthority('activiti:formData:query')")
    @ApiOperation("查询所有")
    @GetMapping(value = "/selectBy")
    @ResponseBody
    public Result selectBy(@ModelAttribute FormDataDto formDataDto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "formData:query");
        Result<FormDataDto> result = new Result<>();

        // 查询条件
        FormData formDataQuery = mapper.map(formDataDto, FormData.class);
        // set deleteflag default 0, 查询参数时，默认只查有效数据
        formDataQuery.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        formDataQuery.rebuildDataLimitQueryBean(userDetailsDto);

        QueryWrapper<FormData> queryWrapper=new QueryWrapper<>(formDataQuery);
        //特殊查询条件
        queryWrapper.ge(formDataDto.getCreateTime_Start()!=null,"create_time",formDataDto.getCreateTime_Start());
        queryWrapper.le(formDataDto.getCreateTime_End()!=null,"create_time",formDataDto.getCreateTime_End());
        queryWrapper.orderBy(formDataDto.getCondition(), formDataDto.isAsc(), formDataDto.getColumn());

        result = formDataService.selectBy(queryWrapper);

        return result;
    }

    //@PreAuthorize("hasAuthority('activiti:formData:query')")
    @ApiOperation("selectById")
    @GetMapping(value = "/selectById")
    @ResponseBody
    public Result selectById(Long id){
        return formDataService.selectById(id);
    }

    //@PreAuthorize("hasAuthority('activiti:formData:query')")
    @ApiOperation("SQL动态多选项, spring动态调用")
    @GetMapping(value = "/select4column")
    @ResponseBody
    public Result select4column(String columnName){
        return formDataService.select4column(columnName);
    }

    //@PreAuthorize("hasAuthority('activiti:formData:create')")
    @ApiOperation("新增对象")
    @PostMapping(value = "/create")
    @ResponseBody
    public Result create(@RequestBody FormDataDto formDataDto, String userDetailsJson){
        //插入参数
        formDataDto.setCreatorUpdatorInfo(userDetailsJson);

        //调用服务
        return formDataService.create(formDataDto);
    }

    // @PreAuthorize("hasAuthority('activiti:formData:update')")
    @ApiOperation("编辑对象")
    @PostMapping(value = "/update")
    @ResponseBody
    public Result update(@RequestBody FormDataDto formDataDto, String userDetailsJson){
        try{
            formDataDto.getId().longValue();
        }catch (Exception e){
            return Result.builder().fault("数据中缺少ID");
        }

        //参数
        formDataDto.setUpdatorInfo(userDetailsJson);

        //调用服务
        return formDataService.updateByDtoId(formDataDto);
    }

    //@PreAuthorize("hasAuthority('activiti:formData:delete')")
    @ApiOperation("逻辑删除对象，由deleteflag控制：0:有效，1:已删除。")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(Long id, String userDetailsJson){
        try{
            id.longValue();
        }catch (Exception e){
            return Result.builder().fault("数据中缺少ID");
        }
        //参数
        FormDataDto formDataDto = new FormDataDto();
        formDataDto.setId(id);
        formDataDto.setUpdatorInfo(userDetailsJson);
        formDataDto.setId(id);
        formDataDto.setDeleteFlag(1);

        //调用服务
        return formDataService.updateByDtoId(formDataDto);
    }

    /*
    @PreAuthorize("hasAuthority('activiti:formData:deletePhysical')")
    @ApiOperation("物理删除对象，默认注释了核心调用方法，请按需启用")
    @PostMapping(value = "/deletePhysical")
    @ResponseBody
    public Result deletePhysical(Long id){
        Result result = new Result();

        //调用服务
        Boolean aBoolean =  false;//formDataService.removeById(id==null?0:id.longValue());
        if(aBoolean){
            result.success();
        }else {
            result.fault();
        }

        return result;
    }
    */

}
